package com.bjsxt.controller;

import com.bjsxt.mapper.AnswerOptDao;
import com.bjsxt.pojo.AnswerOpt;
import com.bjsxt.pojo.Question;
import com.bjsxt.pojo.QuestionOpt;
import com.bjsxt.pojo.Survey;
import com.bjsxt.service.QuestionServer;
import com.bjsxt.service.SurveyServer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Controller
@RequestMapping("/record")
public class RecordController {

    @Autowired
    private SurveyServer surveyServer;
    @Autowired
    private QuestionServer questionServer;
    @Autowired
    private AnswerOptDao answerOptDao;


    @GetMapping("/page")
    public String page(){
        return "survey/recordPage";
    }



    /**
     * 选项统计页面跳转
     * @return
     */
    @GetMapping("/record/{id}")
    public String record(@PathVariable("id") Integer id, ModelMap modelMap){

        Survey survey = surveyServer.detail(id);

        Question question = new Question();
        question.setSurveyId(survey.getId());
        List<Question> questionList = questionServer.query(question);


        AnswerOpt answerOpt = new AnswerOpt();
        answerOpt.setSurveyId(id);
        List<AnswerOpt> optList = surveyServer.queryAnswer(answerOpt);

        Set<String> set = new HashSet<>();

        for (AnswerOpt answerOpts : optList) {
            //利用set集合的特性去重
            set.add(answerOpts.getVoter());
        }

        for (Question question1 : questionList) {
            for (QuestionOpt option : question1.getOptions()) {
                int num = 0;
                for (AnswerOpt opt : optList) {
                    if (option.getId() == opt.getOptId()){
                        num++;
                    }

                }
                //循环完当前选项并记录被选次数
             option.setNum(num);
            }
        }


        survey.setQuestions(questionList);
        modelMap.addAttribute("survey",survey);
        modelMap.addAttribute("totle",set.size());

        return "survey/record";
    }

}
